package com.ls.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.entity.BookNote;
import com.ls.entity.Booking;
import com.ls.service.IBookNoteService;
import com.ls.service.IBookingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static com.ls.constant.SystemConstants.*;

/**
 * 清除预定轮询
 */
@Slf4j
@Component
public class ClearBookingTask {
    @Autowired
    private IBookingService bookingService;
    @Scheduled(cron = "${schedule.booking.cron}")
    public void clearBooking(){
        // 获取所有预定
        List<Booking> bookingList = bookingService.list(new LambdaQueryWrapper<Booking>()
                .notIn(Booking::getBookingStatus, Arrays.asList(4, 5))
        );
        log.info("开始清除预定：{}", bookingList);
        log.info("获取到的预定长度：{}", bookingList.size());
        if (bookingList == null || bookingList.size() == 0 || bookingList.isEmpty()) {
            return;
        }
        for (Booking booking : bookingList) {
            log.info("开始清除预定：{}", booking);
            // 获取预定时间
            LocalDateTime bookingDateTime = LocalDateTime.of(booking.getBookingDay(), booking.getEndTime());
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            // 判断预定时间是否小于当前时间
            if (bookingDateTime.isBefore(now)) {
                log.info("清除预定：{}", booking);
                // 删除预定
                booking.setBookingStatus(4);
                booking.setUpdateTime(LocalDateTime.now());
                bookingService.updateById(booking);
                BookNote bookNote = new BookNote();
                bookNote.setBookingId(booking.getBookingId());
                bookNote.setCustomerId((long) NUMBER_0);
                bookNote.setLinkmanId(booking.getLinkmanId());
                bookNote.setBookingSource(6);
                bookNote.setBookingStatus(booking.getBookingStatus());
                bookNote.setBookingContent(bookingService.getContent(booking));
                bookNote.insert();
            }
        }
    }
}
